package info.emamian.droplet.core.smsHandler;

import info.emamian.droplet.core.domain.BasicSMS;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

public class DrugInfoHandler extends AbstractSMSHandler {

	private static final Logger log = LoggerFactory.getLogger(DrugInfoHandler.class);

	Map<String, String> map = new HashMap<String, String>();

	public DrugInfoHandler(ApplicationContext applicationContext) throws IOException {
		loadFromFile(applicationContext, "drugs.csv");
	}

	@Override
	protected String processAnswer(BasicSMS sms) {
		if (sms.getFirstWord().equalsIgnoreCase("drug")) {
			if (sms.getWords().size() < 2) {
				return getUsage();
			}
			String key = sms.getBody().substring(sms.getFirstWord().length()).trim().toLowerCase();
			if (key == null || key.isEmpty())
				return getUsage();

			if (key != null && key.length() > 0 && map.containsKey(key)) {
				return map.get(key);
			} else {
				if (key.length() > 100)
					key = key.substring(0, 100) + "...";
				return "No drug information found for: " + key;
			}
		}
		return null;
	}

	@Override
	public String getUsage() {
		return "drug [drug name]";
	}

	private void loadFromFile(ApplicationContext applicationContext, String filename) throws IOException {
		// ServletContextResource resource = new
		// ServletContextResource(servletContext, filename);
		// BufferedReader br = new BufferedReader(new
		// InputStreamReader(servletContext.getResourceAsStream(filename)));
		BufferedReader br = new BufferedReader(new FileReader(applicationContext.getResource("/WEB-INF/drugs.csv").getFile()));
		log.info("reading file" + new Date());
		String line;
		String nl = "null".intern();
		int emptyLine = 0;
		int malfrmed = 0;
		int keyEmpty = 0;
		int valEmpty = 0;
		int valNull = 0;
		int bigVal = 0;
		int dotError = 0;
		int commaError = 0;
		int spaceError = 0;
		HashMap<Integer, Integer> sizes = new HashMap<Integer, Integer>();
		while ((line = br.readLine()) != null) {
			line = line.trim();
			if (line.isEmpty()) {
				emptyLine++;
				continue;
			}
			String[] str = line.split("\",\"");
			if (str.length < 3) {
				malfrmed++;
				continue;
			}
			if (str[0].length() < 2) {
				keyEmpty++;
				continue;
			}
			if (str[2].length() < 2) {
				valEmpty++;
				continue;
			}
			String key = str[0].substring(1).trim();
			String val = str[2].substring(0, str[2].length() - 1).trim();
			if (key.isEmpty()) {
				keyEmpty++;
				continue;
			}
			if (val.isEmpty()) {
				valEmpty++;
				continue;
			}
			if (val.equalsIgnoreCase(nl)) {
				valNull++;
				continue;
			}
			if (val.length() > 160) {
				bigVal++;
				int idx = val.lastIndexOf(".", 160);
				if (idx != -1) {
					log.info("idx . " + idx + " : " + val.substring(0, idx));
					val = val.substring(0, idx);
				} else {
					dotError++;
					idx = val.lastIndexOf(",", 157);
					if (idx != -1) {
						System.err.println("idx2 , " + idx + " : " + val.substring(0, idx));
						val = val.substring(0, idx) + "...";
					} else {
						commaError++;
						idx = val.lastIndexOf(" ", 157);
						if (idx != -1) {
							System.err.println("KIDDING space " + idx + " : " + val.substring(0, idx));
							val = val.substring(0, idx) + "...";
						} else {
							spaceError++;
							System.err.println("RUN FOREST : " + val);
						}
					}
				}

			}
			map.put(key.toLowerCase(), val);
			if (!sizes.containsKey(val.length())) {
				sizes.put(val.length(), 1);
			} else {
				sizes.put(val.length(), sizes.get(val.length()) + 1);
			}
		}
		br.close();
		log.info("Emtpy Line :" + emptyLine);
		log.info("malformed :" + malfrmed);
		log.info("key empty :" + keyEmpty);
		log.info("val empty :" + valEmpty);
		log.info("val null :" + valNull);
		log.info("big :" + bigVal);
		log.info("err :" + dotError);
		log.info("zlen :" + commaError);
		log.info("try3 :" + spaceError);
		log.info(sizes.toString());
	}
}
